// 将整数转换成 时：分：秒的格式
function realFormatSecond(second) {
  var secondType = typeof second;

  if (secondType === "number" || secondType === "string") {
    second = parseInt(second);

    var hours = Math.floor(second / 3600);
    second = second - hours * 3600;
    var mimute = Math.floor(second / 60);
    second = second - mimute * 60;

    return hours + ":" + ("0" + mimute).slice(-2) + ":" + ("0" + second).slice(-2);
  } else {
    return "0:00:00";
  }
}

var timer_1,
  timer_2,
  timer_hb,
  powerToast = null; // 循环定时器
var gitClickLove;

var onMessageReceived = null;
let videoFirst = 0; //第一次初始化
let firstInitPlay = true;

import { Toast } from "vant";
import html2canvas from "html2canvas";
import ClickLove from "../../live/clickLove";

// IM Web SDK
import TIM from "tim-js-sdk";
// 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
let tim = null; // SDK 实例通常用 tim 表示

var self = null;
var player;

var _h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
export default {
  data() {
    let that = this;
    return {
      previewImageUrl: null,
      stopLive: false,
      isAddLove: false,
      songStop: true,
      sliderTime: 0,
      targetVideo: {
        // 该字段是音频是否处于播放状态的属性
        playing: false,
        // 音频当前播放时长
        currentTime: 0,
        // 音频最大播放时长
        maxTime: 0,
        minTime: 0,
        step: 0.1
      },
      loadedVideoDataOk: false,
      clientWidths: document.body.clientWidth,
      stopLiveTest: "直播已结束",
      swiperResize: false,
      isOpenIM: false,
      isSuccessIM: false,
      RoomId: null,
      showPoster: false,
      showGoodLift: false,
      mainCommentShow: false,
      maincomment: "",
      MemberInfo: {},
      radio: "1",
      dataInfo: {},
      tipsopacity: 0,
      tipsContent: [],
      tipsContentMsssage: {},
      tipsopacityBol: false,
      view_num: 1,
      lasttime: null,
      messageList: [],
      commentMessage: "和主播说点什么...",
      PosterDatas: {}, //海报数据
      posterImg: [],
      base64Datas: [],

      loadingImg: true,
      failUpload: false,
      dataURL: "",
      activeSwiperIndex: 0,
      liveList: [], //直播列表
      liveSrc: "",
      LiveFlvSrc: "",
      liveHeight: _h,
      isPlaying: false,
      isMiniprogram: false,

      diy_menu: [], //悬浮菜单
      diy_option: [], //更多选项
      diy_set: [], //功能开关，为空时就是全都开启
      //more
      isLoadMore: true,
      page: 1,
      total_page: 0,
      show: false,
      openRTC: false, //是否开启rtc协议
      liveRTCSrc: "",
      mode_button: 0, //0为竖屏，1为横屏
      swiperOption: {
        direction: "vertical",
        observer: true,
        observerParents: true,
        updateOnWindowResize: true,
        initialSlide: 0, //设定初始化时slide的索引。
        width: that.fun.getPhoneEnv() != 3 ? document.documentElement.clientWidth : "375",
        height: that.fun.getPhoneEnv() == 2 ? window.screen.availHeight : window.innerHeight,
        // height:window.innerHeight,
        watchOverflow: true,
        autoHeight: true,
        autoplay: false,
        pagination: false,
        on: {
          reachEnd() {
            //回调函数，当Swiper切换到最后一个Slide时执行。
            if (videoFirst === 1) {
              that.getMoreData();
            }
          },
          slideChangeTransitionEnd() {
            //回调函数，swiper从一个slide过渡到另一个slide结束时执行。
            console.log("回调函数，swiper从一个slide过渡到另一个slide结束时执行。", that.liveList[this.realIndex].id ,this.realIndex);
            // that.onPlayerPause();
            if (that.isOpenIM && that.isSuccessIM) {
              that.quitGroup();
              setTimeout(() => {
                that.logout(); //退出聊天室
              }, 1000);
            }
            that.quitRoom(); //退出直播间
            tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
            that.initData();
            that.activeSwiperIndex = this.realIndex;

            if (this.realIndex === 0) {
              that.liveList[this.realIndex].show = false;
              that.liveList[this.realIndex + 1].show = false;
            } else {
              that.liveList[this.realIndex - 1].show = false;
              that.liveList[this.realIndex].show = false;
              if (that.liveList[this.realIndex + 1]) {
                that.liveList[this.realIndex + 1].show = false;
              }
            }
            that.RId = that.liveList[this.realIndex].id;
            that.getLiveRoom();
            // 切换时当前链接更换且不刷新页面 start======
            let _link = `${that.fun.getSiteRoot()}/addons/yun_shop/?menu#/shareRoom/player?i=${that.fun.getKeyByI()}&mid=${that.fun.getKeyByMid()}`;
            _link = `${_link}&RId=${that.RId}&STAT=${that.STAT}&REC=${that.REC}&CAT=${that.CAT}`;
            window.history.replaceState("", "", _link);
            //  切换时当前链接更换且不刷新页面 end======
            //切换结束时
          },
          resize() {
            //窗口变化了
            that.setSwiperH();
          }
        }
      }
    };
  },
  mounted() {
    firstInitPlay = true;
    player = null;
    this.isMiniprogram = window.isMiniprogram;
    if (this.fun.isIosOrAndroid() == "ios" && window.sessionStorage.getItem("videoReload") === null) {
      window.sessionStorage.setItem("videoReload", true);
      location.reload();
    }
  },

  activated() {
    self = this;
    player = null;
    this.$store.commit("setReturnLiveBtn", false);
    if (!document.getElementById("TcPlayerJs")) {
      //避免多次引入
      const script = document.createElement("script");
      script.type = "text/javascript";
      if (window.location.host.indexOf("localhost") > -1) {
        script.src = this.fun.getSiteRoot() + "/static/app/TcPlayer-2.4.1.js";
      } else {
        script.src = this.fun.getSiteRoot() + "/addons/yun_shop/static/app/TcPlayer-2.4.1.js";
      }
      script.id = "TcPlayerJs";
      document.body.appendChild(script);
      script.onload = script.onreadystatechange = function() {
        if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
          console.log("js onload");
          self.getLiveList();
        }
        script.onload = script.onreadystatechange = null; //删除事件处理函数。
      };
    } else {
      self.getLiveList();
    }

    firstInitPlay = true;

    let {CAT,STAT,REC,RId} = this.$route.query;
    this.RId = RId;
    this.CAT = CAT||'';
    this.STAT = Number(STAT)||'';
    this.REC = REC||'';

    this.activeSwiperIndex = 0;
    this.initData();

    this.$nextTick(() => {
      this.startMove();
    });
    window.onresize = function() {
      if (!self.mainCommentShow && !self.showGoodLift) {
        _h = window.screen.availHeight + "px";
        document.querySelector("video").style.height = _h;
        document.getElementsByClassName("vcp-player")[0].style.height = _h;
        return;
      }
    };
  },
  deactivated() {
    if (player) {
      player.destroy(); //销毁播放器实例
      player = null;
    }

    tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
    if (this.isOpenIM && this.isSuccessIM) {
      this.quitGroup();
    }
    this.quitRoom();
    setTimeout(() => {
      this.logout();
      tim = null;
    }, 80);

    clearInterval(timer_1);
    clearTimeout(timer_hb);
    if (powerToast) {
      //取消海报生成提示，防止退出直播间后还在提示
      powerToast.clear();
    }
    window.onresize = function() {};
  },
  methods: {
    getIMSDKAppID(sdkappid) {
      if(!sdkappid) return;
      // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
      tim = TIM.create({ SDKAppID: sdkappid });// 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
      // SDK 实例通常用 tim 表示
      // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
      // tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
      tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用

    },
    resizeH() {
      if (this.fun.getPhoneEnv() == 2) {
        let hh = window.screen.availHeight + "px";
        document.querySelector("video").style.height = hh;
        document.getElementsByClassName("vcp-player")[0].style.height = hh;
      }
    },
    addClickLove() {
      this.addLoveNum();
      if (!this.isAddLove) {
        this.isAddLove = true;
        $http
          .get("plugin.share-room.frontend.controllers.index.room-like", { room_id: this.RId }, "")
          .then(response => {
            if (response.result == 1) {
              let newNum = Number(this.dataInfo.like_count) + 1;
              this.$set(this.dataInfo, "like_count", newNum);
            } else {
              Toast(response.msg);
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
      gitClickLove.likeClick();
    },
    previewImage() {
      if (this.fun.getPhoneEnv() == 1) {
        return;
      }
      let that = this;
      wx.previewImage({
        current: that.previewImageUrl,
        urls: [that.previewImageUrl]
      });
    },
    setTcPlayer() {
      let that = this;
      player = new TcPlayer("videoPlayer", {
        live: this.STAT == 1 ? true : false,
        x5_type: "h5",
        x5_fullscreen: true,
        systemFullscreen: true,
        x5_orientation: 1,
        x5_player: true,
        flash: false,
        webrtc: this.liveRTCSrc,
        m3u8: this.liveSrc, //请替换成实际可用的播放地址
        autoplay: false, //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
        width: that.fun.getPhoneEnv() != 3 ? window.innerWidth : "375", //视频的显示宽度，请尽量使用视频分辨率宽度
        height: this.liveHeight, //视频的显示高度，请尽量使用视频分辨率高度
        wording: {
          2032: "请求视频失败，请检查网络",
          2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
        },
        controls: "none",
        Flash: false,
        listener: function(msg) {
          if (msg.type == "loadeddata") {
            console.log("loadeddata===============");
            that.resizeH();
            // that.onPlayerPlay();
          }
          if (msg.type == "loadedmetadata") {
            // console.log("loadedmetadata==》》》》》",parseInt(player.video.el.duration));
            that.targetVideo.maxTime = parseInt(player.video.el.duration);
          }
          if (msg.type == "load") {
            timer_2 = setTimeout(() => {
              that.loadedVideoDataOk = true;
            }, 800);
          }
          if (msg.type == "error") {
            console.log("error::视频播放不了.....");
            Toast("该视频出现问题了！");
            that.show = true;
            that.loadedVideoDataOk = true;
            that.$set(that.liveList[that.activeSwiperIndex], "show", true);
          }
          if (msg.type == "play") {
            that.videoPlaying();
            clearInterval(timer_2);
          }
          if (msg.type == "playing") {
            that.songStop = false;
            // that.videoPlaying();
          }
          if (msg.type == "pause") {
            that.songStop = true;
          }
          if (msg.type == "timeupdate") {
            that.targetVideo.currentTime = player.video.el.currentTime;
            that.sliderTime = parseInt((that.targetVideo.currentTime / that.targetVideo.maxTime) * 100);
          }
        }
      });
    },
    noAutoPlaying() {
      player.play();
    },
    videoPlaying() {
      console.log("videoPlaying方法.......");
      let that = this;
      this.show = true;
      this.$set(this.liveList[this.activeSwiperIndex], "show", true);
      this.isPlaying = this.fun.getPhoneEnv() == 2 ? true : false;
      this.$nextTick(() => {
        setTimeout(() => {
          that.CanvasInit(); //防止取不到dom
        }, 500);
      });
      if (player.playing()) {
        console.log("正在播放视频.......");
      }
    },
    setSwiperH() {
      this.swiperResize = true;
      let that = this;
      setTimeout(() => {
        console.log("setSwiperH方法，SwiperH高度发送变化", window.innerHeight);
        that.swiperOption.height = window.innerHeight;
        that.swiperOption.initialSlide = that.activeSwiperIndex;
        that.swiperResize = false;
      }, 80);
      setTimeout(() => {
        that.CanvasInit(); //防止取不到dom
      }, 500);
    },
    CanvasInit() {
      let likeid = document.getElementById("likeid");
      let bg = document.getElementById("canvasImg");
      gitClickLove = new ClickLove(likeid, bg);
    },
    onPlayerPause() {
      player.pause();
    },

    initData() {
      // player = null;
      powerToast = null;
      clearTimeout(timer_hb);
      this.previewImageUrl = null;
      this.stopLive = false;
      this.isAddLove = false;
      this.loadedVideoDataOk = false;
      this.isOpenIM = false;
      this.isSuccessIM = false;
      this.show = false;
      this.showPoster = false;
      this.showGoodLift = false;
      this.mainCommentShow = false;
      this.maincomment = "";
      this.MemberInfo = {};
      this.radio = "1";
      this.dataInfo = {};
      this.tipsopacity = 0;
      this.tipsContent = [];
      this.tipsContentMsssage = {};
      this.tipsopacityBol = false;
      this.view_num = 1;
      this.lasttime = null;
      this.messageList = [];
      this.commentMessage = "和主播说点什么...";

      this.PosterDatas = {};
      this.posterImg = [];
      this.base64Datas = [];
      this.loadingImg = true;
      this.failUpload = false;
      this.dataURL = "";
      this.liveRTCSrc = "";
      this.liveSrc = "";
      this.LiveFlvSrc = "";
      this.songStop = true;
      this.sliderTime = 0;
      this.diy_menu = []; //悬浮菜单
      this.diy_option = []; //更多选项
      this.diy_set = []; //功能开关，为空时就是全都开启
      this.targetVideo = {
        // 该字段是音频是否处于播放状态的属性
        playing: false,
        // 音频当前播放时长
        currentTime: 0,
        // 音频最大播放时长
        maxTime: 0,
        minTime: 0,
        step: 0.1
      };

    },
    logout() {
      let promise = tim.logout();
      promise
        .then(function(imResponse) {})
        .catch(function(imError) {
          console.warn("logout error:", imError);
        });
    },
    //聊天登录
    chatLogin() {
      let that = this;
      let promise = tim.login({
        userID: that.dataInfo.userID.toString(),
        userSig: that.dataInfo.userSig
      });
      promise
        .then(function(imResponse) {
          setTimeout(() => {
            that.chatJoinGroup();
          }, 1000);
        })
        .catch(function(imError) {
          console.warn("login error:", imError); // 登录失败的相关信息
        });
    },
    chatEventList() {
      let that = this;
      onMessageReceived = function(event) {
        // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
        // event.name - TIM.EVENT.MESSAGE_RECEIVED
        // event.data - 存储 Message 对象的数组 - [Message]
        //防止重新接受两条信息
        if (event.data[0].type == "TIMCustomElem" && event.data[0].payload && event.data[0].payload.extension == "customText") {
          if (that.lasttime == event.data[0].time) {
            return;
          } else {
            that.lasttime = event.data[0].time;
          }
        }
        let message = event.data;
        message.forEach(function(val, index) {
          let conversationType = val.conversationType;
          //判断消息来源群或者个人
          console.log("有信息===================", val);
          if (conversationType == TIM.TYPES.CONV_GROUP) {
            let data = val;
            //后台发送过来的消息处理
            if (data.from == "administrator") {
              if (data.payload.extension == "virtual_view_num") {
                //观看人数
                if (data.payload.description && data.payload.extension == that.dataInfo.setting.im_type) {
                  let json = JSON.parse(data.payload.description);
                  that.view_num = json.view_num;
                  that.dataInfo.like_count = json.like_num;
                }
              } else if (data.payload.extension == "buy") {
                //正在买
                if (data.payload.description) {
                  let json = JSON.parse(data.payload.description);
                  that.tipsContent.push({
                    type: "buy",
                    nickname: json.nickname,
                    count: json.count
                  });
                }
              } else if (data.payload.extension == "end") {
                //直播已结束
                that.stopLive = true;
                that.stopLiveTest = "直播已结束";
              } else if (data.payload.extension == "ban") {
                //直播间被禁
                that.stopLive = true;
                that.stopLiveTest = "直播间被禁";
              } else if (data.payload.extension == "leave") {
                //主播暂时离开
                that.stopLive = true;
                that.stopLiveTest = "主播暂时离开";
              } else if (data.payload.extension == "online") {
                //主播重新连接
                that.stopLiveTest = "主播重新连接中...";
                player.load(this.openRTC ? that.liveRTCSrc : that.liveSrc);
                setTimeout(() => {
                  that.stopLive = false;
                }, 1000);
              }
            } else if (data.type == "TIMCustomElem") {
              //自定义类型解析
              if (data.payload.extension == "customText") {
                let messageListData = JSON.parse(data.payload.description);
                console.log("有聊天信息", messageListData);
                that.messageList.push(messageListData);
                that.$nextTick(() => {
                  that.chatMessagesBottom();
                });
              } else if (data.payload.extension == "come") {
                //进入直播间
                if (data.payload.description) {
                  let json = JSON.parse(data.payload.description);
                  that.tipsContent.push({
                    type: "come",
                    nickname: json.nickname
                  });
                }
              } else if (data.payload.extension == "welcome") {
                //进入直播间自动回复
                let json = JSON.parse(data.payload.description);
                console.log("进入直播间自动回复", json);
                that.messageList.push(json);
                that.$nextTick(() => {
                  that.chatMessagesBottom();
                });
              } else if (data.payload.extension == "addlove") {
                gitClickLove.likeClick();
              }
            }
          } else if (conversationType == TIM.TYPES.CONV_C2C) {
            console.log("进入直播间自动");
          }
        });
      };
      // 监听事件，例如：
      tim.on(TIM.EVENT.SDK_READY, function(event) {
        // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
        // console.log("收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口")
        that.chatMyProfile();
        // event.name - TIM.EVENT.SDK_READY
      });
      tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
      tim.on(TIM.EVENT.KICKED_OUT, function(event) {
        // 收到被踢下线通知
        // event.name - TIM.EVENT.KICKED_OUT
        // event.data.type - 被踢下线的原因，例如:
        //    - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
        //    - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
        //    - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢
        Toast("下线通知：您的IM在其他设备登录！");
      });
    },
    chatMyProfile() {
      let that = this;
      let promise = tim.getMyProfile();
      promise
        .then(function(imResponse) {
          // console.log("个人资料 - Profile 实例",imResponse.data); // 个人资料 - Profile 实例
          let myData = imResponse.data;
          if (!myData.nick) {
            that.changeMyProfile();
          }
        })
        .catch(function(imError) {
          console.warn("getMyProfile error:", imError); // 获取个人资料失败的相关信息
        });
    },
    //修改我的个人信息
    changeMyProfile() {
      let that = this;
      let promise = tim.updateMyProfile({
        nick: that.dataInfo.userNickname,
        avatar: that.dataInfo.userAvatar
      });
      promise
        .then(function(imResponse) {
          // console.log(imResponse.data); // 更新资料成功
        })
        .catch(function(imError) {
          console.warn("updateMyProfile error:", imError); // 更新资料失败的相关信息
        });
    },
    //获取群详细资料
    chatJoinGroup() {
      let that = this;
      let promise = tim.joinGroup({
        groupID: that.dataInfo.groupId,
        type: TIM.TYPES.GRP_CHATROOM
      });
      promise
        .then(function(imResponse) {
          switch (imResponse.data.status) {
          case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
            break; // 等待管理员同意
          case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
            console.log("加群成功", imResponse.data.group); // 加入的群组资料
            that.isSuccessIM = true;
            that.$nextTick(() => {
              that.comeLiveRoom();
            });
            break;
          default:
            break;
          }
        })
        .catch(function(imError) {
          console.warn("joinGroup error:", imError); // 申请加群失败的相关信息
        });
    },
    quitGroup() {
      //退出群组
      let that = this;
      if (this.isSuccessIM) {
        let promise = tim.quitGroup(that.dataInfo.groupId);
        promise
          .then(function(imResponse) {
            console.log("退出成功的群", imResponse.data.groupID); // 退出成功的群 ID
          })
          .catch(function(imError) {
            console.warn("quitGroup error:", imError); // 退出群组失败的相关信息
          });
      }
    },
    //发送聊天
    sendmessage() {
      if (!this.isSuccessIM) {
        return;
      }
      this.catMessage("text", this.maincomment);
    },
    //创建聊天模版
    catMessage(type, text) {
      let that = this;
      let messageData = {};
      let Json = {
        memberId: this.dataInfo.userID ? this.dataInfo.userID : "",
        nickName: this.dataInfo.userNickname ? this.cutNameLimit(this.dataInfo.userNickname) : "",
        memberAvatar: this.dataInfo.userAvatar ? this.dataInfo.userAvatar : "",
        text: text ? text : ""
      };
      switch (type) {
      case "text":
        messageData = {
          to: that.dataInfo.groupId,
          conversationType: TIM.TYPES.CONV_GROUP,
          payload: {
            data: "自定义文本", // 用于标识该类型消息
            description: JSON.stringify(Json),
            extension: "customText"
          }
        };
        break;
      }
      let message = tim.createCustomMessage(messageData);
      let promise = tim.sendMessage(message);
      promise
        .then(function(imResponse) {
          // 发送成功
          if (type == "text") {
            that.messageList.push(Json);
            that.clearSend();
            that.$nextTick(() => {
              that.chatMessagesBottom();
            });
          }
        })
        .catch(function(imError) {
          // 发送失败
          if (type == "text") {
            that.clearSend();
          }
          console.warn("sendMessage error:", imError);
        });
    },
    subMainCommentBtn() {
      let that = this;
      this.mainCommentShow = true;
      setTimeout(() => {
        that.$nextTick(() => {
          that.$refs.commentInput.focus();
        });
      }, 200);
    },
    cutNameLimit(_name) {
      if (_name.length > 8) {
        return _name.slice(0, 8) + "...";
      }
      return _name;
    },
    isBlur() {
      setTimeout(() => {
        this.mainCommentShow = false;
      }, 500);
      this.commentMessage = this.maincomment ? this.maincomment : "和主播说点什么";
      var currentPosition, timerIn;
      var speed = 1; //页面滚动距离
      timerIn = setInterval(function() {
        currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
        currentPosition -= speed;
        window.scrollTo(0, currentPosition); //页面向上滚动
        currentPosition += speed; //speed变量
        window.scrollTo(0, currentPosition); //页面向下滚动
        clearInterval(timerIn);
      }, 1);
    },
    clearSend() {
      let that = this;
      this.$nextTick(() => {
        that.$refs.commentInput.blur();
      });
      this.maincomment = null;
      this.commentMessage = "和主播说点什么...";
      this.mainCommentShow = false;
    },
    clickMessageOverlay() {
      this.commentMessage = this.maincomment ? this.maincomment : "和主播说点什么...";
    },
    chatMessagesBottom() {
      this.messageList = this.messageList.slice(-100);
      let ele = document.getElementById("chat_messages");
      if (ele) ele.scrollTop = ele.scrollHeight; // 使滚动条保持在底部
    },
    comeLiveRoom() {
      this.catComeMessage();
      // this.catWelcomeMessage();
    },
    //创建进入直播间自定义模版
    catComeMessage() {
      let that = this;
      let messageData = {};
      let Json = {
        memberId: this.dataInfo.userID ? this.dataInfo.userID : "",
        nickname: this.dataInfo.userNickname ? this.dataInfo.userNickname : ""
      };

      messageData = {
        to: that.dataInfo.groupId,
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          data: "自定义文本", // 用于标识该类型消息
          description: JSON.stringify(Json),
          extension: "come"
        }
      };

      let message = tim.createCustomMessage(messageData);
      let promise = tim.sendMessage(message);
      promise
        .then(function(imResponse) {
          // 发送成功
          that.tipsContent.push({
            type: "come",
            nickname: Json.nickname
          });
        })
        .catch(function(imError) {
          // 发送失败
          console.warn("进入直播间提示失败:::", imError);
        });
    },
    //创建进入直播间欢迎文字模版
    catWelcomeMessage() {
      let that = this;
      let messageData = {};
      let Json = {
        content: '欢迎进入直播间'
      };

      messageData = {
        to: that.dataInfo.groupId,
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          data: "自定义文本", // 用于标识该类型消息
          description: JSON.stringify(Json),
          extension: "welcome"
        }
      };

      let message = tim.createCustomMessage(messageData);
      let promise = tim.sendMessage(message);
      promise
        .then(function(imResponse) {
          // 发送成功
          that.messageList.push(Json);
          that.$nextTick(() => {
            that.chatMessagesBottom();
          });
        })
        .catch(function(imError) {
          // 发送失败
          console.warn("进入直播间自动回复提示失败:::", imError);
        });
    },
    //点赞
    addLoveNum() {
      let that = this;
      let messageData = {
        to: that.dataInfo.groupId,
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          data: "点赞", // 用于标识该类型消息
          description: JSON.stringify({}),
          extension: "addlove"
        }
      };

      let message = tim.createCustomMessage(messageData);
      let promise = tim.sendMessage(message);
      promise
        .then(function(imResponse) {
          console.warn("点赞imResponse:::", imResponse);
        })
        .catch(function(imError) {
          // 发送失败
          console.warn("点赞失败:::", imError);
        });
    },

    getLiveList() {
      // 获取直播列表，并把当前的直播间数据插在第一个
      this.liveList = [];
      $http
        .post("plugin.share-room.frontend.controllers.index.room-list", { category_id: this.CAT, status: this.STAT, is_recommend: this.REC }, "")
        .then(response => {
          if (response.result === 1) {
            this.isLoadMore = true;
            this.total_page = response.data.list.last_page;
            let _livelistes = response.data.list.data;

            this.liveList.push({
              id: this.RId,
              show: false
            });
            if (_livelistes.length > 0) {
              _livelistes.forEach(x => {
                if (x.id != this.RId) {
                  this.liveList.push(x);
                }
              });
            }

            this.getLiveRoom();
            this.setSwiperH();
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    getMoreData() {
      console.log("触发更多：：：getMoreData");
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        return;
      } else {
        this.page = this.page + 1;
        let _url = 'plugin.share-room.frontend.controllers.index.room-list';
        let json = { page: this.page, category_id: this.CAT, status: this.STAT, is_recommend: this.REC };
        $http.post(_url, json, "加载中").then((response) => {
          this.isLoadMore = true;
          if (response.result === 1) {
            var myData = response.data.list.data;
            this.liveList = this.liveList.concat(myData); //数组拼接
          } else {
            this.page = this.page - 1;
            this.isLoadMore = false;
            return;
          }
        }
        );
      }
    },

    getLiveRoom() {
      $http
        .post("plugin.share-room.frontend.controllers.index.room-detail", { room_id: this.RId }, "")
        .then(response => {
          videoFirst = 1;
          if (response.result === 1) {
            if(response.data.status == 0){
              return this.$router.push(this.fun.getUrl('shareRoomForeshow', {}, {RId: this.RId, CAT: this.CAT, STAT: this.STAT, REC: this.REC}));//还未开播，跳转到预告
            }
            this.stopLive = false;
            this.mode_button = response.data.mode_button || 0; //是否竖屏横屏
            this.$set(this.liveList[0], "avatar", '');//共享直播没有主播头像，换成商城logo
            this.$set(this.liveList[0], "nickname", response.data.nickname);
            // this.$set(this.liveList[0], "banner", response.data.image_url);
            this.$set(this.liveList[0], "banner", 'https://test-1251768088.cos.ap-guangzhou.myqcloud.com/image/ee74f94a8e364b385c79d0de5dac8be9.png');


            this.dataInfo = response.data;
            this.view_num = response.data.total_num ? response.data.total_num : 1;
            // this.liveSrc = 'http://1251768088.vod2.myqcloud.com/0a2a9670vodcq1251768088/4bf88a1a243791576611984147/playlist_eof.m3u8';
            this.openRTC = response.data.play_url.play_url_webrtc ? true : false;
            let _playURL = response.data.status == 2 ? response.data.play_back_url : response.data.play_url.play_url_hls;
            this.liveSrc = this.replaceURLHttp(_playURL);
            this.liveRTCSrc = this.openRTC ? this.replaceURLHttp(response.data.play_url.play_url_webrtc) : ""; //voice_open：是否开启rtc模式
            this.LiveFlvSrc = response.data.play_url.play_url_flv;
            if (firstInitPlay) {
              this.getIMSDKAppID(response.data.setting.sdkappid);
              console.log("初始化TcPlayer===================");
              this.setTcPlayer();
              firstInitPlay = false;
            } else {
              player.load(this.openRTC ? this.liveRTCSrc : this.liveSrc);
            }
            if (response.data.is_account_import == 1 && response.data.setting.sdkappid) {
              this.isOpenIM = true;
              this.chatEventList(); //加载聊天事件
              setTimeout(() => {
                this.chatLogin();
              }, 1000);
            } else {
              this.isOpenIM = false;
            }
            this.diy_menu = response.data.diy_menu.reverse();
            setTimeout(() => {
              this.fun.wxShare(
                "",
                {},
                {
                  title: this.liveList[this.activeSwiperIndex]?.title || "直播间邀请",
                  imgUrl: this.liveList[this.activeSwiperIndex]?.cover||"",
                  description: this.dataInfo.userNickname + "邀请您进入" + this.liveList[this.activeSwiperIndex].nickname + "的直播间"
                }
              );
              // this.getPoster();

            }, 1200);
          } else {
            Toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    quitRoom() {
      //退出当前直播间
      $http.post("plugin.share-room.frontend.controllers.index.quit-room", { room_id: this.RId }, "").then(response => {}).catch(error => {console.log(error);});
    },

    showPosterMethob(_tag) {
      let that = this;
      if (!this.loadingImg && this.dataURL) {
        clearTimeout(timer_hb);
        if (powerToast) {
          powerToast.clear();
        }

        if (that.failUpload) {
          return;
        }
        this.showPoster = true;
        if (this.fun.getPhoneEnv() == 2) {
          Toast({
            duration: 3500,
            message: "点击海报预览后,可长按保存！"
          });
        }
        return;
      } else {
        if (!powerToast) {
          powerToast = Toast({
            duration: -1, // 持续展示 toast
            message: "正在为您生成海报中，请稍后"
          });
        }
        timer_hb = setTimeout(() => {
          that.showPosterMethob(true);
        }, 800);
      }
    },
    getPoster() {
      powerToast = Toast({
        duration: -1, // 持续展示 toast
        message: "正在为您生成海报中，请稍后"
      });
      $http
        .post("plugin.share-room.frontend.controllers.index.room-post", { room_id: this.RId })
        .then(response => {
          if (response.result === 1) {
            this.posterImg.push(this.$store.state.temp.mailInfo?.logo, this.dataInfo.userAvatar, response.data.qr_code);
            this.loop();
          } else {
            Toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });


    },
    async loop() {
      let that = this;
      for (let i = 0; i < that.posterImg.length; i++) {
        await that.onloadImg(that.posterImg[i], i);
      }
      this.$nextTick(() => {
        setTimeout(() => {
          console.log("开始画图");
          that.saveImg();
        }, 1000);
      });
    },
    onloadImg(data, i, type) {
      return new Promise((resolve, reject) => {
        //一定要设置为let，不然图片不显示
        let image = new Image();
        //解决跨域问题
        image.setAttribute("crossOrigin", "anonymous");

        let imageUrl = data;
        // let scale = window.devicePixelRatio; //定义任意放大倍数 支持小数
        image.src = `${imageUrl}?${Date.now()}`;
        let that = this;
        //image.onload为异步加载
        image.onload = () => {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);

          var quality = 0.8;
          //这里的dataurl就是base64类型
          var dataURL = canvas.toDataURL("image/png", quality); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
          that.base64Datas.push(dataURL);
          console.log("转换图片成功 =====success=====", i);
          resolve();
        };
        image.onerror = () => {
          that.base64Datas.push("");
          console.log("转换图片报错  ===== error ===", i);
          resolve();
        };
      });
    },
    saveImg() {
      var content = document.getElementById("code_box");
      const that = this;
      if (content) {
        html2canvas(content, {
          useCORS: true,
          backgroundColor: null // 解决生成的图片有白边
        }).then(canvas => {
          that.dataURL = canvas.toDataURL("image/png"); //创建base64图片
          document.getElementById("thecanvas").setAttribute("src", that.dataURL);
          that.uploadImageM();
        });
      }
    },
    uploadImageM() {
      //图片上传
      let that = this;
      let uploadImage = this.fun.getRealUrl("upload.uploadPic", {});
      let fd = new FormData();
      fd.append("file", this.dataURItoBlob(this.dataURL));
      axios
        .post(uploadImage, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          if (response.data.result == 1) {
            that.previewImageUrl = response.data.data.img_url;
            that.loadingImg = false;
            that.showPosterMethob();
          } else {
            that.loadingImg = false;
            that.failUpload = true;
            Toast(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    dataURItoBlob(dataURI) {
      // 图片转成Buffer---------------------------------
      var byteString = atob(dataURI.split(",")[1]);
      var mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    startMove() {
      let that = this;
      if (this.tipsContent.length > 0) {
        this.tipsopacityBol = !this.tipsopacityBol;
      }
      timer_1 = setTimeout(() => {
        if (this.tipsopacityBol) {
          if (this.tipsContent.length > 0) {
            (that.tipsContentMsssage = that.tipsContent.shift()), (that.tipsopacity = 1);
          } else {
            that.tipsopacity = 0;
          }
        } else {
          this.tipsopacity = 0;
        }
        this.startMove();
      }, 2000); // 滚动不需要停顿则将2000改成动画持续时间
    },

    gotoGoodDetail(_id) {
      if (window.isMiniprogram) {
        return this.gotoMini(`/packageA/detail_v2/detail_v2?id=${_id}&share_room_id=${this.RId}`);
      }
      this.$router.push(this.fun.getUrl("goods", { id: _id }, { share_room_id: this.RId }));
    },

    cloneFloatBtn(index) {
      this.diy_menu.splice(index, 1);
      return;
    },
    gotoLivelist() {
      // 微信
      if (window.isMiniprogram) {
        return this.gotoMini('/mircoApp/share-room/list/list');
      }
      if (window.history.length <= 1) {
        this.$router.push(this.fun.getUrl("shareRoomList", {}));
      } else {
        this.$router.go(-1);
      }
    },
    toSetURL(item){
      if (window.isMiniprogram) {
        return this.gotoMini(item.mini_url);
      }
      window.location.href = item.url;
    },
    gotoMini(url){
      wx.miniProgram.navigateTo({
        url: url
      });
    },

    shareMessage() {
      this.$dialog.alert({ message: "点击生成海报分享给您的好友！" });
    },
    // 处理进度条start
    changePlayStatus() {
      if (this.songStop) {
        player.play();
      } else {
        player.pause();
      }
    },
    handleTouchStart(e) {
      this.setValue(e.touches[0]);

      document.addEventListener("touchmove", this.handleTouchMove);
      document.addEventListener("touchup", this.handleTouchEnd);
      document.addEventListener("touchend", this.handleTouchEnd);
      document.addEventListener("touchcancel", this.handleTouchEnd);
      // e.preventDefault();
    },
    handleTouchMove(e) {
      this.setValue(e.changedTouches[0]);
    },
    handleTouchEnd(e) {
      this.setValue(e.changedTouches[0]);
      document.removeEventListener("touchmove", this.handleTouchMove);
      document.removeEventListener("touchup", this.handleTouchEnd);
      document.removeEventListener("touchend", this.handleTouchEnd);
      document.removeEventListener("touchcancel", this.handleTouchEnd);
    },
    // 从点击位置更新 value
    setValue(e) {
      let that = this;
      const { maxTime, minTime, step } = that.targetVideo;
      let value = ((e.clientX - that.$refs.slider[0].offsetLeft) / that.$refs.slider[0].offsetWidth) * (maxTime - minTime);
      value = Math.round(value / step) * step + minTime;
      value = parseFloat(value.toFixed(5));

      if (value > maxTime) {
        value = maxTime;
      } else if (value < minTime) {
        value = minTime;
      }
      this.sliderTime = parseInt((value / maxTime) * 100);
      player.currentTime(value);
    },

    gotoUrl(name, params = {}) {
      this.$router.push(this.fun.getUrl(name, params));
    },
    replaceURLHttp(data) {
      let url = data;
      if (url.match("^http://")) {
        url = url.replace("http://", "https://"); //将http链接替换为https，解决苹果电脑浏览器移动端模式播放失败问题
      }
      return url;
    }
  },
  beforeRouteLeave: function(to, from, next) {
    if (self.showPoster) {
      self.showPoster = false;
      next(false);
    } else {
      next();
    }
  },
  computed: {

    swiper() {
      return this.$refs.mySwiper.swiper;
    },
    playsinline() {
      var ua = navigator.userAgent.toLocaleLowerCase();
      if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        return false;
      } else {
        return true;
      }
    },
    nameEllipsis() {
      if (this.dataInfo.userNickname) {
        return this.dataInfo.userNickname + "的分享";
      }
    }
  },
  components: {},
  filters: {
    // 将整数转化成时分秒
    formatSecond(second = 0) {
      return realFormatSecond(second);
    }
  }
};
